package net.sf.midollo.net.protocol.multitunnel;

import java.io.IOException;
import java.io.InterruptedIOException;

import net.sf.midollo.io.IOStream;
import net.sf.midollo.io.IOStreamConnector;

public class MultiTunnelSession extends IOStreamConnector {

  protected final MultiTunnelManager manager;
  protected final int sessionId;

  public MultiTunnelSession(MultiTunnelManager manager, int sessionId, IOStream ioStream, int bufSize) throws IOException {
    super(ioStream, bufSize);
    this.manager = manager;
    this.sessionId = sessionId;
  }

  public int getSessionId() {
    return this.sessionId;
  }

  public void runConnector() throws IOException {
    int nread, available;
    while (true) {
      try {
        available = this.is.available();
        available = available <= 0 ? 1 : (available > this.buffer.length ? this.buffer.length : available);
        // Utils.log("MTS" + this.sessionId + " R" + available);
        nread = this.is.read(this.buffer, 0, available);
      } catch (InterruptedIOException e) {
        nread = e.bytesTransferred;
      }
      if (nread < 0) {
        break;
      }
      synchronized (this.manager.lock) {
        // Utils.log("MTS" + this.sessionId + " W" + nread);
        this.manager.writeToTunnel(this.sessionId, this.buffer, 0, nread);
      }
    }
    // Utils.log("MTS" + this.sessionId + " end");
  }

  public void destroySession() throws IOException {
  }
}
